#!/usr/bin/python2.4

import urllib
import urllib2

from mod_python import apache

class UrlFactory:
    BASE_URL = 'http://picasaweb.google.com/data/feed/api/user'

    def MakeAlbumListUrl(user):
        return '%s/%s?kind=album&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user)
        )
    MakeAlbumListUrl = staticmethod(MakeAlbumListUrl)

    def MakeAlbumUrl(user, album):
        return '%s/%s/album/%s?kind=photo&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user),
            urllib.quote(album.replace(' ', ''))
        )
    MakeAlbumUrl = staticmethod(MakeAlbumUrl)

    def MakeAlbumIdUrl(user, albumid):
        return '%s/%s/albumid/%s?kind=photo&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user),
            urllib.quote(albumid)
        )
    MakeAlbumIdUrl = staticmethod(MakeAlbumIdUrl)

    def MakePhotoIdUrl(user, photoid):
        return '%s/%s/photoid/%s?kind=photo&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user),
            urllib.quote(photoid)
        )
    MakePhotoIdUrl = staticmethod(MakePhotoIdUrl)


# TODO(caffeine): modify to pass through If-Modified-Since and send back 304s
def __execute__(req, url):
    resp = None
    try:
        resp = urllib2.urlopen(url)
    except urllib2.URLError, e:
        #req.content_type = 'text/plain'
        #req.write('URLGrabError: %d for URL %s' % (e.code, url))

        if e.code > 400 and e.code < 600:
            req.status = e.code
        else:
            req.status = apache.HTTP_INTERNAL_SERVER_ERROR

    req.content_type = 'application/json; charset=UTF-8'
    req.write(resp.read())
    req.status = apache.HTTP_OK


def albumlist(req, user):
    url = UrlFactory.MakeAlbumListUrl(user)
    __execute__(req, url)

def album(req, user, album):
    url = UrlFactory.MakeAlbumUrl(user, album)
    __execute__(req, url)

def albumid(req, user, albumid):
    url = UrlFactory.MakeAlbumIdUrl(user, albumid)
    __execute__(req, url)

def photoid(req, user, photoid):
    url = UrlFactory.MakePhotoIdUrl(user, photoid)
    __execute__(req, url)
